package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final String  SING = "!Q@W3e4r%T^Y";

    public static String getToken(Map<String,String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,60);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));//sign
        return token;
    }

    public static Map<String , String> verifyAndUpdate(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        Map<String, Claim> map = decodedJWT.getClaims();

        Calendar expiredTime = Calendar.getInstance();
        expiredTime.setTime(decodedJWT.getExpiresAt());

        Calendar currentTime = Calendar.getInstance();
        currentTime.add(Calendar.MINUTE , 30);

        Map<String , String> result = new HashMap<>();

        if(currentTime.after(expiredTime)){
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE,60);//默认7天过期

            JWTCreator.Builder builder = JWT.create();
            map.forEach((k,v)->{
                builder.withClaim(k,v.asString());
            });

            String updatedToken = builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                    .sign(Algorithm.HMAC256(SING));//sign

            result.put("update" , "true");
            result.put("token" , updatedToken);
        }
        else {
            result.put("update" , "false");
        }

        String id = decodedJWT.getClaim("id").asString();
        System.out.println("jwt中的id是" + id );
        result.put("id" , id);

        return result;
    }
}
